package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class FileService {
    @Value("${avatar.path}")
    private String avatarExternalPath;

    public String storeFile(MultipartFile file) {
        // 1. 确保外部目录存在（不存在则创建）
        File dir = new File(avatarExternalPath);
        if (!dir.exists()) {
            dir.mkdirs(); // 递归创建目录
        }
        if (StringUtils.isBlank(file.getOriginalFilename())){
            throw new BusinessException("文件名称解析失败");
        }
        String[] split = file.getOriginalFilename().split("\\.");
        // 2. 保存文件到外部目录（文件名用 userId 避免冲突）
        String filename = UUID.randomUUID() +"."+ split[1];
        File dest = new File(avatarExternalPath + filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
        // 3. 返回访问 URL（前端通过 http://域名/avatars/123.jpg 访问）
        return "/avatars/" + filename;
    }

    public void deleteFile(String fileName) {
        File dest = new File(avatarExternalPath + fileName);
        if (dest.exists()) {
            dest.delete();
            log.info("{}deleted", fileName);
        }
    }


}
